package com.pg_chat.service;

import com.alibaba.fastjson.JSONObject;
import com.pg_chat.mapper.FriendsMapper;
import com.pg_chat.model.FriendsEntity;
import com.pg_chat.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service("friendsService")
public class FriendsServiceImpl implements FriendsService{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    FriendsMapper friendsMapper;

    @Override
    public JSONObject friendsList(String userId) {

        try {
            Integer userIdInt = Integer.parseInt(userId);
            List<FriendsEntity> friends = friendsMapper.queryFriendsByUserId(userIdInt);
            JSONObject json = new JSONObject();
            if (friends != null) {
                json.put("item", JsonUtil.convertObj2JSON(friends));
                json.put("total",friends.size());
                return json;
            }else if(friends == null){
                json.put("item","你还没有朋友,快去添加好友吧！");
                json.put("total",0);
                return json;
            }
        }catch (Exception e){
            logger.error("通过用户id查找好友信息异常！",e);
        }
        return null;
    }

    @Override
    public JSONObject updateFriends(List<FriendsEntity> friends) {
        JSONObject json = new JSONObject();
        Boolean isSuccess = false;
        Integer total = friends.size();
        Integer execute = 0;
        String message = "添加好友f失败";
        for(FriendsEntity friend: friends){
            int result = friendsMapper.updateFriends(friend);
            if(result != 1)
                message = message.replaceAll("f",friend.getFriName()+",f");
            execute ++;
        }
        message = message.replaceAll(",f|f","");
        if(execute.equals(total)) {
            message = "添加成功";
            isSuccess = true;
        }
        json.put("message",message);
        json.put("isSuccess",isSuccess);

        return json;
    }

    @Override
    public Boolean addFriends(List<Map<String, FriendsEntity>> friends) {
        return null;
    }

    @Override
    public Boolean deleteFriends(List<Map<String, FriendsEntity>> friends) {
        return null;
    }
}
